package com.quyunshuo.module.home.fragment.me

import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.animation.LinearInterpolator
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.quyunshuo.edwinmusictwo.base.BaseApplication
import com.quyunshuo.edwinmusictwo.common.ui.BaseFragment
import com.quyunshuo.module.home.R
import com.quyunshuo.module.home.activity.main.SharedViewModel
import com.quyunshuo.module.home.databinding.HomeFragmentMeBinding
import com.quyunshuo.module.home.music.LyricAdapter
import com.quyunshuo.module.home.music.LyricLine
import com.quyunshuo.module.home.music.LyricParser
import com.quyunshuo.module.home.music.MusicPlayer
import com.quyunshuo.module.home.music.VerticalSpaceItemDecoration
import com.quyunshuo.module.home.view.GradientProgressBar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


/**
 * @author DBoy 2021/7/6 <p>
 * - 文件描述 : 测试fragment
 */
@AndroidEntryPoint
class MeFragment : BaseFragment<HomeFragmentMeBinding, MeViewModel>() {
    override val mViewModel by viewModels<MeViewModel>()
    override fun createVB() = HomeFragmentMeBinding.inflate(layoutInflater)
    val sharedViewModel: SharedViewModel by activityViewModels()
    private var rotateAnimator: ObjectAnimator? = null
    private val handler = Handler(Looper.getMainLooper())
    private val updateLyrics = object : Runnable {
        override fun run() {
            updateLyricView()
            handler.postDelayed(this, 200) // 每200ms更新一次
        }
    }

    override fun HomeFragmentMeBinding.initListener() {
        play.setOnClickListener {
            val currentMusic = MusicPlayer.getCurrentMusic()
            val currentIndex = MusicPlayer.getCurrentIndex()
            //如果还没播放过，那么就选第一首
            if (currentMusic == null) {
                MusicPlayer.getMusicList()?.apply {
                    MusicPlayer.init(BaseApplication.context, this[0], 0)
                    //同步更新。
                    sharedViewModel.setCurrentMusic( this[0])
                }

                return@setOnClickListener
            }

            currentMusic?.apply {
                MusicPlayer.init(BaseApplication.context, this, currentIndex)

            }
        }
        previousMusic.setOnClickListener {
            MusicPlayer.playPrevious(BaseApplication.context)
        }
        nextMusic.setOnClickListener {
            MusicPlayer.playNext(BaseApplication.context)
        }
        progressBar.setOnProgressChangeListener(object :GradientProgressBar.OnProgressChangeListener{
            override fun onProgressChanged(
                progressBar: GradientProgressBar,
                progress: Float,
                fromUser: Boolean
            ) {
                if (fromUser && MusicPlayer.getCurrentMusic() != null) {
                    // 计算目标位置（毫秒）
                    val targetPosition = (progress / 100f * MusicPlayer.getCurrentMusic()!!.duration).toInt()
                    MusicPlayer.seekTo(targetPosition)

                }
            }

        })
    }


    @RequiresApi(Build.VERSION_CODES.O)
    override fun HomeFragmentMeBinding.initView() {
        rotateAnimator = ObjectAnimator.ofFloat(cover, "rotation", 0f, 360f).apply {
            duration = 10000 // 3秒完成一次旋转
            interpolator = LinearInterpolator() // 线性插值器使旋转平滑
            repeatCount = ValueAnimator.INFINITE // 无限循环
            start()
        }
        // 初始化歌词视图
        setupLyricsView()

        // 加载歌词
        loadLyrics()

    }
    private lateinit var lyricAdapter: LyricAdapter
    private var lyrics = listOf<LyricLine>()

    private fun setupLyricsView() {
        lyricAdapter = LyricAdapter(emptyList())
        mBinding.lyricsRecyclerView.apply {
            layoutManager = LinearLayoutManager(requireActivity())
            adapter = lyricAdapter
            addItemDecoration(VerticalSpaceItemDecoration(16))
        }
    }

    private fun loadLyrics() {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                // 从raw资源读取歌词（实际应用中从文件读取）
                val inputStream = resources.openRawResource(R.raw.live)
                val lrcContent = inputStream.bufferedReader().use { it.readText() }

                // 解析歌词
                lyrics = LyricParser.parseLrc(lrcContent)

                // 更新UI
                withContext(Dispatchers.Main) {
                    lyricAdapter = LyricAdapter(lyrics)
                    mBinding.lyricsRecyclerView.adapter = lyricAdapter
                }
            } catch (e: Exception) {
                Log.e("Lyrics", "加载歌词失败", e)
                withContext(Dispatchers.Main) {
                    lyrics = listOf(LyricLine(0, "暂无歌词"))
                    lyricAdapter = LyricAdapter(lyrics)
                    mBinding.lyricsRecyclerView.adapter = lyricAdapter
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        rotateAnimator?.cancel()
    }

    override fun initObserve() {

        lifecycleScope.launch {
            sharedViewModel.currentMusic.collect {
                it?.apply {
                    Log.d("wenlong", "initObserve: ${getLyricPath(it.path)}")

                    mBinding.musicTitle.text = it.title
                    mBinding.musicContent.text = it.album
                    mBinding.sumCount.text = MusicPlayer.formatDuration(it.duration)
                }
            }
        }
        lifecycleScope.launch {
            sharedViewModel.isPlaying.collect {
                if (it) {
                    mBinding.play.setImageResource(R.drawable.stop)
                    handler.post(updateLyrics)
                } else {
                    mBinding.play.setImageResource(R.drawable.start)
                    handler.removeCallbacks(updateLyrics)
                }
            }
        }
        lifecycleScope.launch {
            sharedViewModel.progress.collect {
                it?.apply {
                    mBinding.currentPropree.text = MusicPlayer.formatDuration(it.first.toLong())
                    // 计算进度百分比并设置到进度条
                    val progressPercent = if (it.second > 0) {
                        (it.first * 100f / it.second).coerceIn(0f, 100f)
                    } else {
                        0f
                    }
//                    mBinding.progressBar.progress = progressPercent.toInt()
                    mBinding.progressBar.setProgress(progressPercent)
                }
            }
        }

    }
    /**
     * 更新歌词视图（高亮当前歌词行并自动滚动）
     *
     * 此方法在播放过程中定期调用，用于：
     * 1. 更新适配器的当前播放位置
     * 2. 查找当前应该高亮的歌词行索引
     * 3. 自动滚动到当前歌词行
     */
    private fun updateLyricView() {
        // 检查播放状态：只有当音乐正在播放时才更新
        if (sharedViewModel.isPlaying.value) {

            // 获取当前播放位置（毫秒）
            val currentPos = MusicPlayer.getCurrentPosition().toLong()

            // 记录当前播放位置（用于调试）
            Log.d("wenlong", "updateLyricView: $currentPos")

            // 更新适配器的当前播放位置
            // 这将触发RecyclerView刷新，使当前歌词行高亮显示
            lyricAdapter.currentPosition = currentPos

            // 查找当前歌词行的索引
            val currentIndex = findCurrentLyricIndex()

            // 如果找到有效的歌词行索引（>=0），则滚动到该位置
            if (currentIndex >= 0) {
                // 使用平滑滚动动画滚动到指定位置
                mBinding.lyricsRecyclerView.smoothScrollToPosition(currentIndex)
            }
        }
    }

    /**
     * 查找当前应该高亮的歌词行索引
     *
     * 根据当前播放位置，在歌词列表中查找：
     * - 当前播放位置所在的时间区间对应的歌词行
     * - 如果找不到匹配项，返回-1
     *
     * @return 当前歌词行的索引，如果未找到返回-1
     */
    private fun findCurrentLyricIndex(): Int {
        // 遍历所有歌词行
        for (i in lyrics.indices) {
            // 处理最后一行歌词的特殊情况
            if (i == lyrics.size - 1) {
                // 如果是最后一行：当前播放位置 >= 该行时间
                if (MusicPlayer.getCurrentPosition() >= lyrics[i].time) {
                    return i // 返回最后一行索引
                }
            } else {
                // 其他行：当前播放位置 >= 该行时间 且 < 下一行时间
                if (MusicPlayer.getCurrentPosition() >= lyrics[i].time &&
                    MusicPlayer.getCurrentPosition() < lyrics[i + 1].time) {
                    return i // 返回当前行索引
                }
            }
        }
        // 没有找到匹配的歌词行
        return -1
    }

    override fun initRequestData() {
    }

    // 根据音频文件路径生成歌词路径
    fun getLyricPath(audioPath: String): String {
        return audioPath.replaceAfterLast(".", "lrc")
    }
}